
import Sprite from '../base/sprite'
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render'

const BG_IMG_SRC = 'pics/background.png'
const TILE_SIZE = 64
const MAP_WIDTH = 10
const MAP_HEIGHT = 15

export default class Background extends Sprite {
  constructor() {
    super(BG_IMG_SRC, TILE_SIZE * MAP_WIDTH, TILE_SIZE * MAP_HEIGHT)
    this.scrollX = 0
    this.scrollSpeed = 1
    this.tiles = []
    this.initTiles()
  }

  initTiles() {
    // 创建10x10地图，随机使用0-3的tile索引
    for (let y = 0; y<MAP_HEIGHT; y++) {
      this.tiles[y] = []
      for (let x = 0; x<MAP_WIDTH; x++) {
        this.tiles[y][x] = Math.floor(Math.random() * 4) // 0-3对应4种tile
      }
    }
  }

  render(ctx) {
    // 计算起始绘制位置
    const startX = Math.floor(this.scrollX / TILE_SIZE)
    const offsetX = this.scrollX % TILE_SIZE

    // 绘制可见区域
    for (let y = 0; y<MAP_HEIGHT; y++) {
      for (let x = startX; x<startX + Math.ceil(SCREEN_WIDTH / TILE_SIZE) + 1; x++) {
        const tileX = x % MAP_WIDTH
        const tileIndex = this.tiles[y][tileX]
        
        // 计算tile在原始图片中的位置
        const srcX = (tileIndex % 2) * TILE_SIZE
        const srcY = Math.floor(tileIndex / 2) * TILE_SIZE
        
        // 绘制tile
        ctx.drawImage(
          this.img,
          srcX, srcY, TILE_SIZE, TILE_SIZE,
          (x - startX) * TILE_SIZE - offsetX, y * TILE_SIZE, TILE_SIZE, TILE_SIZE
        )
      }
    }

    // 更新滚动位置
    this.scrollX += this.scrollSpeed
    if (this.scrollX >= TILE_SIZE * MAP_WIDTH) {
      this.scrollX = 0
    }
  }
}